package io.github.iogogogo.commons.support;

import jakarta.annotation.Resource;
import lombok.Data;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.info.GitProperties;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author tao.zeng6@asiainfo.com
 * @since 2025/7/29 09:44
 */
@Data
@Component
@ConditionalOnProperty(prefix = "project.version", name = "enabled", havingValue = "true")
public class VersionManager implements InitializingBean {

    @Resource
    private GitProperties gitProperties;

    private String version, commitId, shortCommitId, fullVersion;

    @Override
    public void afterPropertiesSet() throws Exception {
        this.commitId = gitProperties.getCommitId();
        this.shortCommitId = gitProperties.getShortCommitId();
        this.version = Optional.ofNullable(gitProperties.get("build.version")).map(String::toString).orElse("unknown");
        this.fullVersion = String.join("-", version, shortCommitId);
    }

    public Map<String, String> versionInfo() {
        Map<String, String> map = new HashMap<>();
        map.put("version", this.getVersion());
        map.put("commit_id", this.getCommitId());
        map.put("short_commit_id", this.getShortCommitId());
        map.put("jdk_info", System.getProperty("java.version"));
        map.put("vm", System.getProperty("java.vm.name"));
        map.put("os", System.getProperty("os.arch"));
        return map;
    }
}
